var express = require('express');
var router = express.Router();
var md5 = require("md5");
// 引入数据库
var usersDAO = require("../bin/cn/usersDAO.js");
// 引入time
var time = require('../bin/libs/time.js');
var isLogin = require('../bin/libs/isLogin.js');

/* 注册用户. */
router.post('/add', function(req, res) {
  if(req.body.yzm.toUpperCase()!==req.session.captcha.toUpperCase()){
    res.json({err:1,msg:"验证码错误"});
    return;
  }
  usersDAO.findOne({username:req.body.username})
  .then(data=>{
    if(data){
      res.json({err:2,msg:"用户名已被占用"});
      return;
    }else{
      usersDAO.findOne({email:req.body.email})
      .then(data=>{
        if(data){
          res.json({err:3,msg:"邮箱已被占用"});
          return;
        }else{
          // 时间戳
          req.body.time = time('time');
          // 加密
          req.body.password = md5(req.body.password);
          req.body.code = 12346;
          var u = usersDAO(req.body);
          u.save()
          .then(function(data){
            req.session.user = data;
            delete req.session.user.password;
            delete req.session.captcha;
            res.json({err:0,msg:"注册成功"});
          })
          .catch(function(){
            res.json({err:4,msg:"数据库插入失败"});
          })
          
        }
      })
    }
  })
  
});

/* 用户登录. */
router.get('/add', function(req, res) {
  req.query.password = md5(req.query.password);
  usersDAO.findOne(req.query,{password:0})
  .then(data=>{
    if(data){
      req.session.user = data
      res.json({err:0,msg:"欢迎  "+data.username});
    }else{
      res.json({err:1,msg:"登录信息错误！"});
    }
  })
  .catch(()=>{
    res.json({err:2,msg:"登录查询错误，稍后再试"});
  })
  
});

/* 退出登录. */
router.get('/exit', function(req, res) {
  delete req.session.user;
  res.json({err:0,msg:"退出成功"});
});

// 查看是否登录，登录返回用户信息，未登录返回状态4
router.get('/isLogin', function(req, res) {
  if(req.session.user){
    res.json({err:0,data:req.session.user});
  }else{
    res.json({err:4,msg:"登录信息已过期"});
  }
});

// 发送验证邮件
// 配置邮件,用于发送电子邮件协议
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
// 邮箱和随机数
var config = require('../bin/libs/config.js')
var strRandom = require('../bin/libs/random.js')

var mailSender = nodemailer.createTransport(smtpTransport({
	service:config.email.service,
	auth:{
		user:config.email.user,
		pass:config.email.pass,
	}
}))
router.get('/retrieve',function(req,res){
  if(req.query.yzm.toUpperCase()!==req.session.captcha.toUpperCase()){
    res.json({err:1,msg:"验证码错误"});
    return;
  };
  usersDAO.findOne({email:req.query.email})
  .then(data=>{
    if(!data){
      res.json({err:2,msg:'邮箱错误'})
    }else{
      
      var num = strRandom(10);
      console.log(111)
      usersDAO.update({email:req.query.email},{$set:{code:num}})
      .then(()=>{
        console.log(114)
          mailSender.sendMail({
          // 发送者
          from:config.email.user,
          to:req.query.email,

          subject:"验证邮件",
          html:`
          <h1>验证邮件</h1>
          <p>请点击下面地址验证邮件</p>
          <a href="http://localhost:8080/#/users/auth/${num}">http://localhost:8080/#/users/auth/${num}</a>
          `
        },function(err){
          if(err){
            console.log("邮件发送失败");
            res.json({err:4,msg:"邮件发送失败"});
          }else{
            console.log("邮件发送成功");
            res.json({err:0,msg:"邮件已经发送您的邮箱"});
          }
        })
      })
      .catch(()=>{
        console.log(137)
        res.json({err:6,msg:"验证码写入数据库错误"});
      })

    }
  })
  .catch(()=>{
    console.log(144)
    res.json({err:3,msg:"邮箱查询失败"});
  })
});
module.exports = router;
